package com.bao.interkont.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.AccessControlList;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectAcl;
import com.aliyun.oss.model.VoidResult;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author bao*
 * @version 1.0
 */
@Slf4j
@Component
public class AliOSSUtils {
    @Autowired
    AliOSSProperties aliOSSProperties;

    public AliOSSUtils() throws ClientException {
    }

    public String upload(MultipartFile image) throws Exception {
        String endpoint = aliOSSProperties.getEndpoint();
        String bucketName = aliOSSProperties.getBucketName();
        String accessKeyID = aliOSSProperties.getAccessKeyID();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();

        InputStream inputStream = image.getInputStream();
        String originalFilename = image.getOriginalFilename();

        int index = originalFilename.lastIndexOf(".");
        String filename = UUID.randomUUID()+originalFilename.substring(index);
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyID,accessKeySecret);
        AccessControlList bucketAcl = ossClient.getBucketAcl(bucketName);
        log.info("{}",bucketAcl.toString());
        ossClient.putObject(bucketName,filename,inputStream);
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + filename;
        ossClient.shutdown();
        return url;
    }

    public String delImage(String fileName) {
        String endpoint = aliOSSProperties.getEndpoint();
        String bucketName = aliOSSProperties.getBucketName();
        String accessKeyID = aliOSSProperties.getAccessKeyID();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        log.info("FILENAME:{}",fileName);
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyID,accessKeySecret);
        AccessControlList bucketAcl = ossClient.getBucketAcl(bucketName);
        try {
            log.info("{}",bucketAcl.toString());
            ossClient.deleteObject(bucketName,fileName);
        } catch (OSSException oe) {
            return oe.toString();
        } finally {
            ossClient.shutdown();
        }
        return bucketAcl.toString();
    }

}
